<?php

namespace App\Console\Commands\Wanggui;

use App\Enums\OpenShop\FeishuMini\SandTableEnum;
use App\Models\OpenShop\SiteLocation\OpenShopSiteLocationExamineLogModel;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class DeleteTestAuditData extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'wanggui:delete-test-audit-data';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '删除点位测试数据点位评估';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     */
    public function handle()
    {
        //设置输入参数
        $userIds = $this->ask('请输入要删除评估的评估人ID(多个用,隔开)');
        if (!$userIds) {
            $userIds = 139;  //王鹏成的RMS_ID
        }

        //设置评估人员的ID,用来当作附加条件
        $userIdArr = explode(',', $userIds);

        //获得该用户已评估的点位
        $userAuditArr = OpenShopSiteLocationExamineLogModel::query()
            ->whereIn('source', [OpenShopSiteLocationExamineLogModel::SOURCE_WG_AUDIT, OpenShopSiteLocationExamineLogModel::SOURCE_OTHER_WG_AUDIT])
            ->whereIn('createdByUid', $userIdArr)
            ->get();

        //RETURN
        if (null == $userAuditArr) {
            return;
        }

        //获得所有评估的点位
        $auditArr = [];
        $userAuditArr->each(function (OpenShopSiteLocationExamineLogModel $shopSiteLocationExamineLogModel) use (&$auditArr) {
            //评估记录去重
            if (!in_array($shopSiteLocationExamineLogModel->orderNo, $auditArr[$shopSiteLocationExamineLogModel->createdByUid] ?? [])) {
                $auditArr[$shopSiteLocationExamineLogModel->createdByUid][] = $shopSiteLocationExamineLogModel->orderNo;
            }
        });

        //根据用户去区分不同的表
        $userAuditBranchTable = [];
        foreach ($auditArr as $userId => $audit) {
            foreach ($audit as $item) {
                $userAuditBranchTable[$userId][substr($item, 0, 2)][] = $item;
            }
        }

        //判断是否为最新的做取舍
        collect($userAuditBranchTable)->each(function ($userAudit, $userId) {
            //逻辑判断
            foreach ($userAudit as $prefix => $audit) {
                //获得前两位匹配不同的表
                $model = SandTableEnum::PREFIX_GET_TABLE_MODEL_MAPPING[$prefix] ?? null;
                //CONTINUE
                if ($model == null) {   //99% KFZC
                    //非数据库根据目前的操纵直接删除就好
                    OpenShopSiteLocationExamineLogModel::query()
                        ->whereIn('source', [OpenShopSiteLocationExamineLogModel::SOURCE_WG_AUDIT, OpenShopSiteLocationExamineLogModel::SOURCE_OTHER_WG_AUDIT])
                        ->where('createdByUid', $userId)
                        ->where('orderNo', $audit)
                        ->update([
                            'updatedAt' => DB::raw('`updatedAt`'),
                            'isDeleted' => 1
                        ]);
                    continue;
                }

                //获得MODEL
                $model::query()
                    ->whereIn('wgNumber', $audit)
                    ->with(['logRel'])
                    ->get()
                    ->map(function ($modelQuery) use ($userId) {
                        $status    = 0;
                        $updatedAt = 0;
                        //判断最后的审批人
                        $modelQuery->logRel
                            ->each(function ($logModel) use (&$status, $userId, &$updatedAt) {
                                if ($logModel->createdByUid != $userId && $updatedAt < $logModel->updatedAt->timestamp) {
                                    $status = $logModel->openPotential;
                                }
                                //删除评估记录
                                if ($logModel->createdByUid == $userId) {
                                    $logModel->isDeleted  = 1;
                                    $logModel->timestamps = false;
                                    $logModel->save();
                                }
                            });
                        //修改网规点位的可开潜力值
                        $modelQuery->status = $status;
                        $modelQuery->save();
                        $this->info($modelQuery->nameText . '已删除');
                    });

            }
        });


    }
}
